<template>
  <div class="">
    <!-- 弹窗 -->
    <el-dialog v-model="store.deptInsertOpen" :show-close="false" append-to-body class="dialogClass" width="36%" draggable overflow >
      <!--弹窗标题-->
      <template #header="{ close, titleId }">
        <div class="dialogHeader">
          <span :id="titleId" class="dlgTitleClass" style="margin: 10px 10px;" v-if="store.updateDeptId==='0'&&!isNaN(store.updateDeptId)">新增</span>
          <span :id="titleId" class="dlgTitleClass" style="margin: 10px 10px; " v-if="store.updateDeptId!=='0'&&!isNaN(store.updateDeptId)">修改</span>
          <el-icon style="font-size: 18px;margin-top: 14px;cursor: pointer" @click="closeDialog">
            <CloseBold/>
          </el-icon>
        </div>
      </template>
      <!--弹窗内容-->
      <template #default>
        <el-form class="menu-form" ref="addDeptFormRef" :rules="rules" :model="addDeptData">
          <el-form-item label="部门类型" prop="deptCategory" >
            <el-radio-group v-model="addDeptData.deptCategory">
              <el-radio border label="年级">年级</el-radio>
              <el-radio border label="班级">班级</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="上级部门" class="parent-select" prop="parentId">
            <el-tree-select
                v-model="addDeptData.parentId"
                :data="parentDeptList"
                check-strictly
                :render-after-expand="false"
                :props="defaultProps"
            />
          </el-form-item>
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="addDeptData.deptName" placeholder="请输入部门名称"></el-input>
          </el-form-item>
          <el-form-item label="部门排序" prop="orderNum" label-width="78px">
            <el-input-number
                v-model="addDeptData.orderNum"
                :min="1"
                :max="999"
                controls-position="right"
            />
          </el-form-item>
        </el-form>
      </template>
      <!--弹窗底部-->
      <template #footer>
        <span class="myDialogFooter">
          <el-button class="el-button__default" @click="closeDialog">取 消</el-button>
          <el-button type="primary" class="el-button__primary" @click="addDeptInfo()" v-if="store.updateDeptId==='0'">确认添加</el-button>
          <el-button type="primary" class="el-button__primary" @click="updateDeptInfo()" v-if="store.updateDeptId!=='0'">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>

import {defineEmits, onMounted, reactive, ref, watch} from "vue";
import {addDeptInfos, getDeptInfoById, getParentDeptList, updateDeptInfos} from "@/api/dept/index.js";
import {CloseBold} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {deptStore} from "@/stores/dept/deptStore.js";
import {BigInteger} from "bignumber";
const addDeptFormRef = ref()
const visible = ref(true);
const emit = defineEmits(['refresh'])
const addDeptData= ref({
  id:0,
  deptName:"",
  parentId:'-000000',
  orderNum:0,
  deptCategory:"年级"
})
const  defaultProps = {
  value:"parentId",
  children: 'children',
  label: `parentName`,
}
const store=deptStore()
onMounted(()=>{
  initParentDeptList()
})
const parentDeptList = ref([{}])
const rules=reactive({
  deptName:[
    {required:true,message:"部门名称不能为空",trigger:"blur"}
  ],
  parentId:[
    {required:true,message:"父级部门不能为空",trigger:"blur"}
  ],
  deptCategory:[
    {required:true,message:"部门类型不能为空",trigger:"blur"}
  ],
  orderNum:[
    {required:true,message:"排序顺序不能为空",trigger:"blur"}
  ]
})

const initParentDeptList = async () => {
const res = await getParentDeptList()
  parentDeptList.value = res.data


}

//观察parentId变化

watch(store,()=>{
  addDeptData.value.parentId=store.parentDeptId
  initParentDeptList()
})

watch(store,()=>{
  if (store.updateDeptId!=='0') {
    initUpdateDeptInfo(store.updateDeptId)
    initParentDeptList()
  }
})
/**
 * 获取
 * @returns {Promise<void>}
 * @param deptId
 */
const initUpdateDeptInfo=async (deptId) => {
  const res = await getDeptInfoById(deptId)
  addDeptData.value=res.data
}
/**
 * 添加部门信息
 * @returns {Promise<void>}
 */
const addDeptInfo = async () => {
 const valid= await addDeptFormRef.value.validate()
 if(valid) {
   try {
     const  parentId=addDeptData.value.parentId
     const resultParentId= isNaN(Number(parentId.split("-")[0]))?0:Number(parentId.split("-")[0])
     const addData={
       deptName:addDeptData.value.deptName,
       deptPid:resultParentId,
       orderNum:addDeptData.value.orderNum,
       deptCategory:addDeptData.value.deptCategory,
       tenantId:parentId.split("-")[1]
     }
     const res = await addDeptInfos(addData)
     ElMessage.success("添加成功")
     await closeDialog()
     emit('refresh')
   }catch (e){
   }
 }
}
const updateDeptInfo =async () => {
  const valid= await addDeptFormRef.value.validate()
  if(valid) {
    ElMessageBox.confirm(
        '此操作将永久修改该部门, 是否继续?',
        '提示', {
          app: undefined, components: undefined, config: undefined, directives: undefined, mixins: [], provides: undefined,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).then(async () => {
      const  parentId=addDeptData.value.parentId
      const resultParentId= isNaN(new BigInteger (parentId.split("-")[0]))?0:new BigInteger(parentId.split("-")[0])
      const addData={
        id:addDeptData.value.id,
        deptName:addDeptData.value.deptName,
        deptPid:resultParentId.toString(),
        orderNum:addDeptData.value.orderNum,
        deptCategory:addDeptData.value.deptCategory
      }

      const res =await updateDeptInfos(addData)
      ElMessage.success("修改成功")
      await closeDialog()
      emit('refresh')
    }).catch(() => {
    })
  }
}
const  closeDialog = () => {
  store.setDeptInsertOpen(false)
  addDeptFormRef.value.resetFields()
  store.setParentDeptId('-000000')
  store.setUpdateDeptId('0')
  addDeptData.value = {
    id:0,
    deptName:"",
    parentId:'-000000',
    orderNum:0,
    deptCategory:"年级"
  }
}
</script>

<style scoped>
.dialogClass .dlgTitleClass {
}

.el-dialog .el-dialog__header {
  margin: 0 !important;
  padding: 0 !important;
}

.el-dialog .dialogHeader {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 40px;
  margin: 0 10px;
  font-size: 18px;
  font-weight: bolder;
}

/* 确保对话框主体可以使用flex布局 */
:deep(.el-dialog__body) {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  padding: 0 50px!important;
}

.menu-form {
  margin:0  50px; /* 自动边距用于水平居中 */
}

.el-dialog .el-dialog__footer {
  padding: 10px;
}

/* 统一选择框、数字框和输入框的宽度 */
.el-input,
.el-input-number,
.el-select,
.el-tree-select{
  --el-select-input-focus-border-color: rgb(46, 92, 246);
  --el-color-primary: rgb(46, 92, 246);
  width: 100%; /* 或者设置一个具体的像素值，比如240px */
  box-sizing: border-box; /* 确保内边距和边框包含在元素的总宽度和高度内 */
}

.el-radio.is-bordered.is-checked {
  --el-color-primary: rgb(46, 92, 246);
}

.el-radio {
  --el-radio-input-border-color-hover: rgb(46, 92, 246);
}
</style>